<template>
  <!-- 权益管理 -->
  <div class="mod-user-userLevelCategory">
    <div class="search-bar">
      <!-- native modifier has been removed, please confirm whether the function has been affected  -->
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="rightsName"
            :label="$t('userRights.rightsName') + ':'"
          >
            <el-input
              v-model="searchForm.rightsName"
              type="text"
              clearable
              :placeholder="$t('userRights.rightsName')"
            />
          </el-form-item>
          <el-form-item
            prop="serviceType"
            :label="$t('user.rightsType') + ':'"
          >
            <el-select
              v-model="searchForm.serviceType"
              clearable
              :placeholder="$t('user.rightsType')"
            >
              <el-option
                v-for="item in status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="resetForm()"
            >
              {{ $t('user.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('user:userRights:save')"
          class="default-btn primary-btn"
          @click="onAddOrUpdate()"
        >
          {{ $t('userRights.customBenefits') }}
        </div>
      </div>
      <div class="table-con">
        <el-table
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
        >
          <el-table-column
            :label="$t('userRights.serialNumber')"
            type="index"
            width="90"
          />
          <el-table-column
            :label="$t('userRights.rightsName')"
            prop="rightsName"
          />
          <el-table-column
            prop="icon"
            :label="$t('userRights.rightsIcon')"
          >
            <template #default="scope">
              <div class="table-cell-image">
                <ImgShow :src="scope.row.icon" />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="description"
            :label="$t('userRights.rightsIntroduce')"
          />
          <el-table-column
            prop="serviceType"
            :label="$t('user.rightsType')"
          >
            <template #default="scope">
              <span>{{ [$t('userRights.systemRights'),$t('userRights.customBenefits')][scope.row.serviceType] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('crud.menu')"
            width="250"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('user:userRights:update')"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.rightsId)"
                >
                  {{ $t('user.revise') }}
                </div>
                <div
                  v-if="scope.row.serviceType === 1 && isAuth('user:userRights:delete')"
                  class="default-btn text-btn"
                  @click="onDelete(scope.row.rightsId)"
                >
                  {{ $t('user.delete') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import AddOrUpdate from './add-or-update.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils/index.js'

const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = reactive({
  rightsName: '',
  serviceType: null
}) // 搜索
const status = [
  {
    label: $t('userRights.systemRights'),
    value: 0
  }, {
    label: $t('userRights.customBenefits'),
    value: 1
  }
]

onMounted(() => {
  getDataList(page)
})

let tempSearchForm = null // 保存上次点击查询的请求条件
const dataList = ref([])
const getDataList = (pageParam, newData = false) => {
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  }
  http({
    url: http.adornUrl('/user/userRights/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    const lang = localStorage.getItem('bbcLang') || 'zh_CN'
    data.records.forEach(element => {
      let rightsNameCn, rightsNameEn, descriptionCn, descriptionEn
      if (!element.userRightsLangList) return
      element.userRightsLangList.forEach(val => {
        if (val.lang === 0) {
          rightsNameCn = val.rightsName
          descriptionCn = val.description
        }
        if (val.lang === 1) {
          rightsNameEn = val.rightsName
          descriptionEn = val.description
        }
      })
      element.rightsName = lang === 'zh_CN' ? rightsNameCn : rightsNameEn || rightsNameCn
      element.description = lang === 'zh_CN' ? descriptionCn : descriptionEn || descriptionCn
    })
    dataList.value = data.records
    page.total = data.total
  })
}

const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(false)
// 新增 / 修改
const onAddOrUpdate = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id)
  })
}

const onDelete = (id) => {
  ElMessageBox.confirm($t('user.isDeleOper'), $t('text.tips'), {
    confirmButtonText: $t('user.confirm'),
    cancelButtonText: $t('user.cancel'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/user/userRights/' + id),
      method: 'delete',
      data: http.adornData({})
    }).then(() => {
      ElMessage({
        message: $t('user.succeeded'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          refreshChange()
        }
      })
    })
  }).catch(() => { })
}

/**
 * 刷新回调
 */
const refreshChange = () => {
  getDataList(page)
}

const onSearch = (newData = false) => {
  page.currentPage = 1
  getDataList(page, newData)
}

const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList(page)
}

const onPageChange = (val) => {
  page.currentPage = val
  getDataList(page)
}

const searchFormRef = ref(null)
const resetForm = () => {
  searchFormRef.value.resetFields()
}

</script>
